﻿Imports System.Text
Imports DevExpress.XtraReports.UI
''' <summary>
''' 
''' </summary>
''' <remarks>Should GO in WinFormExt not in CommonExt... Dependency on DevExp component - AL 2013-06-03 </remarks>
Public Class RptNotification

    ''' <summary>
    ''' Get The Report Definition from the database
    ''' </summary>
    ''' <param name="reportName"></param>
    ''' <returns></returns>
    ''' <remarks>Make sure the Reportname is unique in the table Metatrings (We use StringCD to store the reportName)</remarks>
    Public Shared Function GetReportFromDB(ByVal reportName As String) As XtraReport
        Dim report As XtraReport = Nothing
        Dim dataFormat As Guid
        Dim binaryString() As Byte


        Using mqReport As MetaQuery = MetaQuery.GetMetaQueryByName("ReadReportFromDocTemplate")
            mqReport.SQLWhere = String.Format("Name = '{0}' ", reportName)
            mqReport.FillResultQuery()
            '
            If mqReport.ResultQuery.Rows.Count = 1 Then
                Dim reportString As String = mqReport.ResultQuery.Rows(0).Item("Data").ToString

                If mqReport.ResultQuery.Rows(0).Item("BinaryData") IsNot DBNull.Value Then
                    binaryString = CType(mqReport.ResultQuery.Rows(0).Item("BinaryData"), Byte())
                    dataFormat = DirectCast(mqReport.ResultQuery.Rows(0).Item("DataFormatId_FK"), Guid)

                    If Not dataFormat = Nothing AndAlso dataFormat = Base.IdRepository.APP_DATAFORMAT_UTF8 Then
                        report = LoadDocument_UsingUTF8(binaryString)

                    ElseIf Not dataFormat = Nothing AndAlso dataFormat = Base.IdRepository.APP_DATAFORMAT_BIN Then
                        LoadDocument(binaryString)
                    End If

                ElseIf Not String.IsNullOrEmpty(reportString) Then
                    'OUSTANDINGISSUE: ancien code qui permet de lire la colonne Data(varchar). On le garde tant qu'on n'a pas converti en varbinary. clieng 2013-01-22.
                    Dim data() As Byte
                    Dim encoder As UTF8Encoding
                    reportString = mqReport.ResultQuery.Rows(0).Item("Data").ToString
                    Using msXmlReportLayout As MemoryStream = New MemoryStream()
                        encoder = New UTF8Encoding()
                        report = New XtraReport()
                        '
                        data = encoder.GetBytes(reportString)
                        msXmlReportLayout.Write(data, 0, data.Length)
                        '
                        report.LoadLayoutFromXml(msXmlReportLayout)
                    End Using
                Else
                    report = New XtraReport()
                    report.Name = reportName
                    'report.DataSourceSchema
                End If

            End If
        End Using
        Return report
    End Function

    ''' <summary>
    ''' Save a Report Definition in the database
    ''' Table use MetaStrings
    ''' </summary>
    ''' <param name="report"></param>
    ''' <returns></returns>
    ''' <remarks>Make sure the Reportname is unique in the table Metatrings (We use StringCD to store the reportName)</remarks>
    Public Shared Function SaveReportInDB(ByVal report As XtraReport, ByVal documentTemplateID As Guid, ByVal categoryID As Guid, ByVal typeID As Guid, ByVal classID As Guid, ByVal dataFormatID As Guid, ByVal queryID As Guid) As Boolean
        Dim sqlcmd As SqlCommand = Nothing

        Dim default_ClassID As Guid = CommonExt.Base.IdRepository.APP_DOCTEMPLATECLASS_RPT
        Dim default_CategoryID As Guid = CommonExt.Base.IdRepository.APP_DOCTEMPLATECATEGORY_REPORT
        Dim default_TypeID As Guid = CommonExt.Base.IdRepository.APP_DOCTEMPLATETYPE_REPX
        Dim default_DataFormatID As Guid = CommonExt.Base.IdRepository.APP_DATAFORMAT_UTF8

        Using reportStream As MemoryStream = New MemoryStream()
            Try
                'pour le sauver dans la BD. Le Format xml semble plus petit a date - aleblanc 2012-12-16
                'report.Tag = Nothing
                report.SaveLayoutToXml(reportStream)
                reportStream.Position = 0

                Using streamReader As StreamReader = New StreamReader(reportStream)

                    sqlcmd = MetaQuery.GetSPCmdByMetaName("ReportBuilder_Save")
                    sqlcmd.Parameters("@DocumentTemplateId").Value = documentTemplateID
                    sqlcmd.Parameters("@CategoryId_FK").Value = IIf(Guid.Empty.Equals(categoryID), default_CategoryID, categoryID)
                    sqlcmd.Parameters("@TypeId_FK").Value = IIf(Guid.Empty.Equals(typeID), default_TypeID, typeID)
                    sqlcmd.Parameters("@ClassId_FK").Value = IIf(Guid.Empty.Equals(classID), default_ClassID, classID)
                    sqlcmd.Parameters("@Name").Value = report.Name
                    sqlcmd.Parameters("@Description").Value = report.Name
                    sqlcmd.Parameters("@Description_ALT").Value = report.Name
                    sqlcmd.Parameters("@DataFormatId_FK").Value = IIf(Guid.Empty.Equals(dataFormatID), default_DataFormatID, dataFormatID)
                    sqlcmd.Parameters("@BinaryData").Value = reportStream.ToArray
                    sqlcmd.Parameters("@QueryID_FK").Value = IIf(Guid.Empty.Equals(queryID), DBNull.Value, queryID)


                    'sqlcmd.Parameters("@Data").Value = streamReader.ReadToEnd
                    'If queryID = Guid.Empty Then
                    '    sqlcmd.Parameters("@QueryID_FK").Value = DBNull.Value
                    'Else
                    '    sqlcmd.Parameters("@QueryID_FK").Value = queryID
                    'End If

                    sqlcmd.ExecuteNonQuery()
                End Using
            Catch ex As Exception
                Throw ex
            Finally
                If sqlcmd IsNot Nothing Then
                    sqlcmd.Connection.Close()
                    sqlcmd.Dispose()
                End If
            End Try
        End Using
        Return True
    End Function

    Public Shared Function LoadDocument_UsingUTF8(ByVal binaryString() As Byte) As XtraReport
        Dim reportString As String
        Dim report As XtraReport = Nothing
        Dim data() As Byte
        Dim encoder As UTF8Encoding
        Try
            Using msXmlReportLayout As MemoryStream = New MemoryStream()
                encoder = New UTF8Encoding()
                report = New XtraReport()
                '
                reportString = Encoding.UTF8.GetString(binaryString)
                data = encoder.GetBytes(reportString)
                msXmlReportLayout.Write(data, 0, data.Length)
                '
                report.LoadLayoutFromXml(msXmlReportLayout)
            End Using
        Catch ex As Exception
            Throw ex
        End Try
        Return report
    End Function

    Public Shared Sub LoadDocument(ByVal binaryString() As Byte)

        'Using fStream As New FileStream("C:\Injurie Copy.pdf", FileMode.CreateNew)
        '    Dim bw As New BinaryWriter(fStream)
        '    bw.Write(binaryString)
        '    bw.Close()
        '    fStream.Close()
        'End Using

        'byte[] binaryString = (byte[])reader[1];

        ' // if the original encoding was ASCII
        ' string x = Encoding.ASCII.GetString(binaryString);

        ' // if the original encoding was UTF-8
        ' string y = Encoding.UTF8.GetString(binaryString);

        ' // if the original encoding was UTF-16
        ' string z = Encoding.Unicode.GetString(binaryString);
    End Sub


    Public Shared Function EncodingObject(ByVal obj As Object, ByVal dataFormatID As Guid) As Byte()
        Dim binaryString() As Byte = Nothing

        Select Case dataFormatID
            Case Base.IdRepository.APP_DATAFORMAT_UTF8
                '
                If TypeOf (obj) Is XtraReport Then
                    Dim aReport As XtraReport = TryCast(obj, XtraReport)
                    Dim encoder As UTF8Encoding = New UTF8Encoding(True)
                    Dim reportString As String

                    Using reportStream As MemoryStream = New MemoryStream()
                        aReport.SaveLayoutToXml(reportStream)

                        Using streamReader As StreamReader = New StreamReader(reportStream)
                            reportString = streamReader.ReadToEnd
                            binaryString = Encoder.GetBytes(reportString)
                        End Using
                    End Using

                End If
            Case Base.IdRepository.APP_DATAFORMAT_BIN

        End Select

        'string myStr = "";
        'using (MemoryStream ms = new MemoryStream()){
        'report.SaveLayout(ms,true);
        'ms.Seek(0, SeekOrigin.Begin);
        'StreamReader sr = new StreamReader(ms);
        'myStr = sr.ReadToEnd();



        Return binaryString
    End Function
End Class
